package com.example.coffeejava.Controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.coffeejava.Dto.Result;
import com.example.coffeejava.Dto.ShopDto;
import com.example.coffeejava.Dto.UserDto;
import com.example.coffeejava.Entity.*;
import com.example.coffeejava.Service.AdminService;
import com.example.coffeejava.Service.ShopService;
import com.example.coffeejava.Service.UserService;
import com.example.coffeejava.utils.RegexUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.example.coffeejava.utils.Constants.*;

@RestController
@RequestMapping("/account")
public class AccountController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private AdminService adminService;
    @Resource
    private UserService userService;
    @Resource
    private ShopService shopService;

    @RequestMapping("/code")
    public Result code(@RequestParam String phone, HttpSession httpSession) {
        if (RegexUtils.isphonevalud(phone)) {
            return Result.error("手机号不合法");
        }
        String code = RandomUtil.randomNumbers(6);
        httpSession.setAttribute("code", code);
        return Result.ok(code);
    }

    @PostMapping("/login")
    public Result login(@RequestBody LoginForm loginForm, HttpSession httpSession) {
        if (RegexUtils.isphonevalud(loginForm.getPhone())) {
            return Result.error("手机号不正确");
        }
        String code = (String) httpSession.getAttribute("code");
        if (!code.equals(loginForm.getCode()) || code == null) {
            return Result.error("验证码不正确");
        }
        if (loginForm.getRole().equals("管理员")) {
            LambdaQueryWrapper<Admin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Admin::getPhone, loginForm.getPhone());
            Admin admin = adminService.getOne(lambdaQueryWrapper);
            if (admin == null) {
                admin = createbyphone(loginForm);
            }
            String token = String.valueOf(UUID.randomUUID());
            UserDto userDto = BeanUtil.copyProperties(admin, UserDto.class);
            //user对象转为HashMap存储
            Map<String, Object> hashMap = BeanUtil.beanToMap(userDto, new HashMap<>(), CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
            String tokenKey = LOGIN_USER_KEY + token;
            stringRedisTemplate.opsForHash().putAll(tokenKey, hashMap);
            stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
            httpSession.removeAttribute("code");
            return Result.ok(token);


        } else if (loginForm.getRole().equals("用户")) {
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getPhone, loginForm.getPhone());
            User user = userService.getOne(lambdaQueryWrapper);
            if (user == null) {
                user = createuserbyphone(loginForm);
            }
            String token = String.valueOf(UUID.randomUUID());
            UserDto userDto = BeanUtil.copyProperties(user, UserDto.class);
            //user对象转为HashMap存储
            Map<String, Object> hashMap = BeanUtil.beanToMap(userDto, new HashMap<>(), CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
            String tokenKey = LOGIN_USER_KEY + token;
            stringRedisTemplate.opsForHash().putAll(tokenKey, hashMap);
            stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
            httpSession.removeAttribute("code");
            return Result.ok(token);


        } else {
            LambdaQueryWrapper<Shop> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Shop::getPhone, loginForm.getPhone());
            Shop shop = shopService.getOne(lambdaQueryWrapper);
            if (shop == null) {
                shop = createshopbyphone(loginForm);
            }
            String token = String.valueOf(UUID.randomUUID());
            UserDto userDto = BeanUtil.copyProperties(shop, UserDto.class);
            //user对象转为HashMap存储
            Map<String, Object> hashMap = BeanUtil.beanToMap(userDto, new HashMap<>(), CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
            String tokenKey = LOGIN_USER_KEY + token;
            stringRedisTemplate.opsForHash().putAll(tokenKey, hashMap);
            stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
            httpSession.removeAttribute("code");
            return Result.ok(token);

        }


    }

    private Shop createshopbyphone(LoginForm loginForm) {
        Shop shop = new Shop();
        shop.setCreateTime(LocalDateTime.now());
        shop.setPhone(loginForm.getPhone());
        shop.setNickName(USER_PREFIX + RandomUtil.randomString(10));
        shop.setUpdateTime(LocalDateTime.now());
        shop.setCertified(UN_CERTIFIED);
        shopService.save(shop);
        return shop;
    }

    @GetMapping("/shopinfo")
    public Result shopinfo() {

        UserDto shopDto = UserHolder.getUser();
        ShopDto shopDto1 = BeanUtil.copyProperties(shopDto, ShopDto.class);
        shopDto1.setCertified(shopService.getById(shopDto.getId()).getCertified());
        return Result.ok(shopDto1);
    }

    @GetMapping("/info")
    public Result info() {
        UserDto userDto = UserHolder.getUser();
        return Result.ok(userDto);
    }

    @PostMapping("/updateinfo")
    @Transactional
    public Result updateuserinfo(HttpServletRequest httpServletRequest, @RequestBody UserDto userDto) {
        System.out.println(userDto);
        User user = new User();
        user.setId(userDto.getId());
        user.setNickName(userDto.getNickName());
        user.setIcon(userDto.getIcon());
        user.setUpdateTime(LocalDateTime.now());
        user.setPhone(userDto.getPhone());
        System.out.println(user);
        userService.updateById(user);
        String token = httpServletRequest.getHeader("authorization");
//        String key=LOGIN_USER_KEY+token;
//      Map<Object,Object> map=stringRedisTemplate.opsForHash().entries(key);
//        UserDto userDto1= BeanUtil.fillBeanWithMap(map,new UserDto(),false);
//        System.out.println(userDto1+"userdit");
        Map<String, Object> hashMap = BeanUtil.beanToMap(userDto, new HashMap<>(), CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        String tokenKey = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey, hashMap);
        return Result.ok("成功");
    }
    @PostMapping("/updateshopinfo")
    @Transactional
    public Result updateshopinfo(HttpServletRequest httpServletRequest, @RequestBody UserDto userDto) {
        System.out.println(userDto);
        Shop shop = new Shop();
        shop.setId(userDto.getId());
        shop.setNickName(userDto.getNickName());
        shop.setIcon(userDto.getIcon());
        shop.setUpdateTime(LocalDateTime.now());
        shop.setPhone(userDto.getPhone());
        System.out.println(shop);
        shopService.updateById(shop);
        String token = httpServletRequest.getHeader("authorization");
//        String key=LOGIN_USER_KEY+token;
//      Map<Object,Object> map=stringRedisTemplate.opsForHash().entries(key);
//        UserDto userDto1= BeanUtil.fillBeanWithMap(map,new UserDto(),false);
//        System.out.println(userDto1+"userdit");
        Map<String, Object> hashMap = BeanUtil.beanToMap(userDto, new HashMap<>(), CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        String tokenKey = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey, hashMap);
        return Result.ok("成功");
    }
    @PostMapping("/sign")
    public Result sign() {
        return userService.sign();

    }

    @GetMapping("/signcount")
    public Result signcount() {
        return userService.signcount();

    }


    private Admin createbyphone(LoginForm loginForm) {
        Admin admin = new Admin();
        admin.setCreateTime(LocalDateTime.now());
        admin.setPhone(loginForm.getPhone());
        admin.setNickName(USER_PREFIX + RandomUtil.randomString(10));
        admin.setUpdateTime(LocalDateTime.now());
        adminService.save(admin);
        return admin;

    }

    private User createuserbyphone(LoginForm loginForm) {
        User admin = new User();
        admin.setCreateTime(LocalDateTime.now());
        admin.setPhone(loginForm.getPhone());
        admin.setNickName(USER_PREFIX + RandomUtil.randomString(10));
        admin.setUpdateTime(LocalDateTime.now());
        userService.save(admin);
        return admin;

    }
    @GetMapping("/count")
    public Result count(){
        return adminService.getcount();
    }
    @GetMapping("/chart")
    public Result chart(){
        return adminService.chart();
    }
    @GetMapping("/chart2")
    public Result chart2(){
        return adminService.chart2();
    }
}
